<script setup lang='ts'>
import { useDebounceFn } from '@vueuse/core'
import { SHORTCUT_RANGE } from '@/constants'

const props = defineProps({
  isms: Boolean, // 返回时间戳（毫秒）
  disabled: Boolean,
  showButton: {
    type: Boolean,
    default: true,
  },
  direction: {
    type: String, // row col
    default: 'row'
  }
})
const emit = defineEmits(['search'])
const range = defineModel()

const timeType = ref('1hour')
const start = ref<Date>()
const end = ref<Date>()

watch(timeType, getRange, { immediate: true })
function getRange() {
  const range = SHORTCUT_RANGE.find(item => item.type === timeType.value)
  if (range.tick) {
    const [s, e] = range.tick()
    start.value = s
    end.value = e
  }
  else {
    start.value = null
    end.value = null
  }
}

watch([start, end], ([s, e]) => {
  if (s && e)
    range.value = [s.getTime(), e.getTime()].map(ms => props.isms ? ms : Math.trunc(ms / 1000))
}, { immediate: true })

const debounceSearch = useDebounceFn(() => {
  // 获取最新时间范围
  if (timeType.value !== 'custom')
    getRange()
  emit('search')
}, 300)
function disabledDate(time: Date) {
  return time.getTime() > Date.now()
}

function reset() {
  timeType.value = '1hour'
}
defineExpose({
  reset,
  getRange,
})
</script>

<template>
  <div :class="{'flex-y-center space-x-2': direction === 'row', 'flex flex-col space-y-2': direction === 'col'}">
    <el-select v-model="timeType" style="width: 96px;">
      <el-option
        v-for="item in SHORTCUT_RANGE"
        :key="item.type"
        :label="item.text"
        :value="item.type"
      />
    </el-select>
    <div v-if="timeType === 'custom'" class="text-nowrap">
      <el-date-picker
        v-model="start"
        :disabled-date="disabledDate"
        type="datetime"
        class="!w-45"
        placeholder="开始时间"
      />
      <span class="px1 text-sm text-#666">至</span>
      <el-date-picker
        v-model="end"
        class="!w-45"
        :disabled-date="disabledDate"
        type="datetime"
        placeholder="结束时间"
      />
    </div>
    <slot />
    <el-button v-if="showButton" type="primary" class="no-border" :disabled="disabled" @click="debounceSearch">
      搜索
    </el-button>
  </div>
</template>

<style scoped lang='scss'>
.el-button--small {
  --el-button-size: 26px !important;
}
</style>
